/*
 * @Author: Han
 * @Date: 2020-08-24 14:17:35
 * @LastEditTime: 2020-08-24 15:13:51
 * @LastEditors: hanfengmi
 * @Description: 
 */
// 基于以下代码完成下面四个练习

const fp = require('lodash/fp')
// 数据
// horsepower 马力， dollar_value 价格， in_stock 库存
const cars = [
    {name:'Ferrari FF',horsepower:660,dollar_value:700000,in_stock:true},
    {name:'Spyker C12 Zagato',horsepower:650,dollar_value:648000,in_stock:false},
    {name:'Jaguar XKR-S',horsepower:550,dollar_value:132000,in_stock:false},
    {name:'Audi R8',horsepower:525,dollar_value:114200,in_stock:false},
    {name:'Aston Martin One-77',horsepower:750,dollar_value:185000,in_stock:true},
    {name:'Pagani Huayra',horsepower:700,dollar_value:130000,in_stock:false},
]
// 一：使用函数fp.flowRight重新实现下面函数
// let isLastInStock = function(cars){
//     // 获取最后一条数据
//     let last_car = fp.last(cars)
//     // 获取最后一条数据的in_stock 属性值
//     return fp.prop('in_stock',last_car)
// }

// console.log('cars',isLastInStock(cars))

// let isLastInStock = fp.flowRight(fp.curry(fp.prop)('in_stock'),fp.last)
let isLastInType = type => fp.flowRight(fp.curry(fp.prop)(type),fp.last)

let isLastInStock = isLastInType('in_stock')
console.log('isLastInStock',isLastInStock(cars))
// let isLastInName = isLastInType('name')
// let isLastInHorsepower = isLastInType('horsepower')
// console.log('isLastInName',isLastInName(cars))
// console.log('isLastInHorsepower',isLastInHorsepower(cars))

// 二：使用函数fp.flowRight()、fp.prop()、fp.first()获取第一个car的name
let isFirstInType = type => fp.flowRight(fp.curry(fp.prop)(type),fp.first)
let isFirstInName = isFirstInType('name')
console.log('isFirstInName',isFirstInName(cars))

// 三：使用帮助函数_average重构averageDollarValue,使用函数组合的方式实现

let _average = function(xs){ //[1,2,3,4,5]
    return fp.reduce(fp.add,0,xs) / xs.length
} // 无需改动

// let averageDollarValue = function(cars){
//     let dollar_value = fp.map(function(car){
//         return car.dollar_value 
//     }, cars)
//     return _average(dollar_value)
// }

// console.log('averageDollarValue',averageDollarValue(cars))
let getValues = fp.curry(fp.prop)('dollar_value');
let averageDollarValue = fp.flowRight(_average,fp.map(getValues))

console.log('averageDollarValue1',averageDollarValue(cars))

// 四：使用flowRight写一个sanitizeNames()函数，返回一个下划线连接的小写字符串，
//    把数组的name转化为这种形式:sanitizeNames(["Hello World"]) => ["hello_world"]
const arr = ['Hello World','Yes I Am','Come On']
let _undersorce = fp.replace(/\W+/g,'_') //无需改动，并在sanitizeNames中使用它
const sanitizeNames = fp.map(fp.flowRight(_undersorce,fp.toLower))
console.log('sanitizeNames',sanitizeNames(arr))